<template>
  <div class="cart">
    <Nav />
    <div v-if="list.length" class="product-title">普通商品</div>
    <Item v-for="(item, idx) in list" :key="idx" :index="item.id" :num="item.number" :max-num="item.maxNum"
      :thumb="item.picUrl" :title="item.goodsName" :desc="item.specifications.join(' ')" 
       :price="item.price | yuan" :price-type="item.priceType" :is-checked="item.checked"
       :point-price="item.pointPrice"
      @input="handleItemSelect" @handleDelete="handleDelete" @changeNum="changeNum" />
    <div v-if="purchaseList.length" class="product-header">
      <div class="product-title">采购商品</div>
      <van-checkbox v-model="isCheckedAll" icon-size="18px" :checked-color="variables.theme"
        style="padding: 0 10px 0 5px; background-color: white" class="product-title" />
    </div>
    <Item v-for="(item, idx) in purchaseList" :key="idx + 10" type="product" :is-show-step="true" :index="item.id"
      :num="item.goodsCount" :max-num="item.goodsCount" :min-number="item.goodsCount" :thumb="item.goodsImg"
      :title="item.goodsName" :price="item.goodsPrice | yuan" :is-checked="item.checked"
      :is-show-right="item.orderPayNoUrl ? item.orderPayNoUrl != null : false"
      @input="handleItemSelect($event, 'purchase', idx, item.checked)" @handleDelete="handleDeletePurchase"
      @changeNum="changeNum" />
    <Tabbar v-if="((list && list.length > 0) || purchaseList.length > 0) && !(isCheckPurchase)" :amount="amount"
      :is-show="isShow" :is-check-purchase="isCheckPurchase" :value="isAllSelect" :time-flag="timeFlag"
      :check-target="checkTarget" :normal-product="isListCheck" :show-check-all="showCheckAll" @confirm="onConfirm"
      @input="handleAllSelect" @add="addShelves('add')" @settle="settlePurchase" @onSubmit="onSubmit" />
    <div v-if="isCheckPurchase" style="
      width: 100%;
      box-sizing: border-box;
      background-color: #fff;
      padding: 0 20px;
      position: fixed;
      bottom: 55px;
      display: flex;
      justify-content: flex-end;
    ">
      <van-button round color="linear-gradient(to right, #ff6034, #ee0a24)" @click="onConfirm('pay')">去付款</van-button>
    </div>
    <Skeleton v-if="isSkeletonShow" />

    <van-empty v-if="list && list.length <= 0" description="小车大容量，喜欢的都加进来吧" />
    <!--    @click="showPaymentVisible = false"-->
    <van-dialog v-model="showPaymentVisible" title="待确认" show-cancel-button @cancel="cancel" @confirm="confirmPay">
      <div style="
          width: 100%;
          color: #333;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          margin-top: 20px;
        ">
        <div class="sale" style="box-sizing:border-box;width: 100%;padding:0 40px;line-height: 30px;">
          <span>余额：</span>
          <span>{{ sale.toFixed(2) }}</span>
        </div>
        <div class="buy" style="box-sizing:border-box;width: 100%;padding:0 40px;line-height: 30px;">
          <span>今日买单金额总计：</span>
          <span>{{ buy.toFixed(2) }}</span>
        </div>
        <div class="else" style="box-sizing:border-box;width: 100%;padding:0 40px;line-height: 30px;">
          <span>{{ '付款金额：' }}</span>
          <span>{{ sale - buy >= 0 ? '余额抵扣，无需付款' : paymentPrice.toFixed(2) }}</span>
        </div>
        <!-- <div v-if="sale-buy>=0" class="tips" style="font-size: 12px; color: #ef3939;margin-top: 20px;">
          注：明天9点前打款！
        </div> -->
      </div>
      <!-- 添加v-if条件判断 -->
      <div v-if="paymentPrice < 0">
        <div style="
            display: flex;
            justify-content: center;
            width: 100%;
            margin-top: 20px;
          ">
          <van-uploader v-model="uploader" multiple :max-count="1" :after-read="afterRead" preview-size="6.9rem" />
        </div>
        <div style="
            width: 100%;
            color: #333;
            display: flex;
            justify-content: center;
            margin-top: 20px;
          ">
          付款码:
        </div>
        <div style="
            width: 100%;
            color: #333;
            display: flex;
            justify-content: center;
            margin-top: 20px;
          ">
          <image-pic :src="paymentUrl" width="200" height="200" />
        </div>
      </div>
    </van-dialog>
    <!--    <van-overlay :show="showPaymentVisible"  z-index="200">-->

    <!--    </van-overlay>-->

  </div>
</template>

<script>
import {
  getCartList,
  updateCart,
  deleteCart,
  getPurchaseProductList,
  updateWarehouseStatus,
  canIDel
} from '@/api/cart';
import { getIsOpenCg } from '@/api/home'
import { mapGetters } from 'vuex';
import Nav from './modules/Nav'
import Item from './modules/Item'
import Tabbar from './modules/Tabbar'
import Skeleton from './modules/Skeleton'
import { checkAddReq, settleCart, getCargoPrice, deletePurchaseCart } from '@/api/cart'
import { getInfo } from '@/api/user'

import { base64uploadFile, base64uploadFileList } from '@/api/upload'
import item from '@/views/cart/modules/Item.vue'
import { orderProcurementHmpay } from '@/api/pay'
import variables from '@/styles/variables.scss'

export default {
  name: 'Cart',
  components: {
    Nav,
    Item,
    Tabbar,
    Skeleton
  },
  data() {
    return {
      list: [],
      amount: 0,
      isAllSelect: false,
      isSkeletonShow: true,
      purchaseList: [],

      timeFlag: false,
      showPaymentVisible: false,
      paymentUrl: '',
      sale: 1000,
      buy: 900,
      paymentPrice: 0,
      uploader: [],
      urls: '',
      checkedAll: false,
      isOkList: [],
      isPay: false,
      userInfo: {}
    }
  },
  computed: {
    showCheckAll() {
      return this.list.length > 0
    },
    isCheckedAll: {
      get() {
        return this.checkedAll
      },
      set(val) {
        if (this.checkedAll === false) {
          if (this.purchaseList.length == 0) {
            return false
          }
          getIsOpenCg().then(res => {
            if (res.map.isOpen == 0) {
              return this.$toast.fail('当前关仓状态中')
            }
            const ids = this.purchaseList.map((item) => {
              return item.id
            })

            getPurchaseProductList().then(res => {
              let newListName = res.map.list.map((item) => {
                return item.goodsName
              })
              let oldNmae = this.purchaseList.map((item) => {
                return item.goodsName
              })
              if (res.map.list.length !== ids.length) {
                this.getList()
                return this.$toast.fail('当前购物车有刷新，请重新点击')
              }
              for (let i = 0; i < newListName.length; i++) {
                if (!oldNmae.includes(newListName[i])) {
                  this.getList()
                  return this.$toast.fail('当前购物车有刷新，请重新点击')
                }
              }

              getCargoPrice({ orderIds: ids.join(','), type: 1 })
                .then(res => {
                  if (res.map.fee.buySuccess == 'success') {
                    this.$toast.fail(res.map.fee.messages)
                    // this.$router.push('/user/order/warehouseList/1?type=1')
                    return false
                  }
                  const data = res.map.fee
                  this.paymentPrice = data.payNum
                  this.sale = data.saleBigDecigmal
                  this.buy = data.buyBigDecigmal
                  this.showPaymentVisible = true
                  this.checkedAll = true
                  this.purchaseList.forEach((item, index) => {
                    item.checked = true
                    this.$set(this.purchaseList, index, item)
                  })
                }).catch(error => {
                  this.$toast.fail(error.message)
                })
            })
          })
          console.log(this.purchaseList)
        }
        return this.checkedAll
      }
    },
    variables() {
      return variables
    },
    isShow() {
      return (
        this.purchaseList.some((item) => item.checked) &&
        this.list.every((item) => !item.checked)
      )
    },
    isCheckPurchase() {
      return this.purchaseList.some((item) => item.checked)
    },
    checkTarget() {
      return this.purchaseList.find((item) => item.checked)
    },
    isListCheck() {
      return this.list.some((item) => item.checked)
    }
  },
  watch: {
    list: {
      handler(newVal) {
        let num = 0
        console.log('newval:', newVal)
        newVal.forEach((item) => {
          if (item.checked) num += parseFloat(item.price) * item.number
        })
        this.isAllSelect = newVal.every((item) => {
          return item.checked === true
        })
        this.amount = num * 100
      },
      deep: true // 开启深度监听
    }
  },
  async mounted() {
    this.checkedAll = false
    this.isPay = false
    this.isCheckedAll = false
    await this.getInfos()
    await this.getList()
    // this.getPurchaseProductDataList()
    // this.addShelves()
  },
  methods: {
    getInfos() {
      getInfo(this.$store.state.user.token)
        .then(res => {
          const data = res.map
          if (!data) {
            return this.$toast.fail('获取用户信息失败')
          }
          this.userInfo = data.info
          this.$set(this, 'userInfo', data.info)
          // commit('SET_USER_INFO', data.info)
          // resolve(data)
        })
    },
    async getIsOpenCgData() {
      const { map: { isOpen } } = await getIsOpenCg()
      return isOpen == 0 ? false : true
    },
    onSubmit() {
      // debugger
      console.log(this.list)
      const typeList = []
      let point = 0
      this.list.forEach((item, index) => {
        if (item.checked === true) {
          typeList.push(item.priceType)
          console.log(item)
          point += (item.pointAmount * item.number)
        }
      })
      console.log(point)
      console.log(this.userInfo.userPoint)

      // debugger
      if (this.list[0].priceType == 2 || this.list[0].priceType == 3) {
        if (point > this.userInfo.userPoint) {
          return this.$toast.fail('积分不足')
        }
      }

      const newList = Array.from(new Set(typeList))
      console.log('newList', newList)
      if (newList.length > 1) {
        return this.$toast.fail('不同支付模式商品禁止同时提交')
      }
      this.$router.push({
        path: '/order/confirm'
      })
    },
    cancel() {
      this.checkedAll = false
    },
    invalid(item) {
      const valid = item.maxNum < item.num
      return valid
    },
    async confirmPay() {
      console.log(this.purchaseList)
      const record = this.checkTarget
      this.checkedAll = true
      console.log(this.purchaseList)
      const ids = this.purchaseList.map((item) => {
        return item.id
      })
      this.showPaymentVisible = false
      console.log('isCheckPurchase', this.isCheckPurchase)
      console.log('checkTarget==', this.checkTarget)
    },
    onCancel() {
      this.urls = ''
      this.showPaymentVisible = false
    },
    async afterRead(file) {
      this.$toast.loading({
        message: '正在上传...',
        forbidClick: true,
        overlay: true
      })
      // 此时可以自行将文件上传至服务器
      const uploadRes = await base64uploadFile({
        base64content: file.content,
        filename: file.file.name
      })
      this.urls = uploadRes.map.fileName
      this.$toast.clear()
      this.$toast.success('上传图片成功')
    },
    async onConfirm(type) {
      // const flag = await canIDelete()
      // if(flag){
      //   return this.$toast.fail('未调单完成，无法支付')
      // }
      this.$toast.loading({ message: '加载中', duration: 5000 })
      console.log('type==', type)
      const record = this.purchaseList
      if (this.isPay) {
        this.timer = setTimeout(() => {
          this.isPay = false
          clearTimeout(this.timer)
        }, 5000)
        window.location.reload()
        return this.$toast.fail('请勿重复提交')
      } else {
        this.isPay = true
      }
      // debugger
      if (type === 'pay') {
        this.paymentUrl = '/upload/' + record.qrCodeUrl
        const ids = this.purchaseList.map((item) => {
          return item.id
        })
        console.log('需支付：', this.paymentPrice)
        if (this.paymentPrice > 0) {
          this.$toast.clear()
          return this.$toast.fail(`余额不足，请联系店长充值${this.paymentPrice}`)

          if (this.purchaseList[0].checked) {
            sessionStorage.setItem('payRedirct', '/user/order/warehouseList/1?type=1')
          }

          // 采购商品支付为2
          sessionStorage.setItem('orderType', 1)
          await this.hmpay({
            payNumber: this.paymentPrice,
            orderIds: ids.join(',')
          })

          /**
           * 测试阶段吊起支付立即调用
           */
          this.purchaseList.map(async (item, index) => {
            await updateWarehouseStatus({
              orderId: item.id,
              payPicUrl: this.payUrl,
              currentSaleStatus: 2
            })
            const list = this.purchaseList.splice(index, 1)
            this.$store.dispatch('user/getCartGoodCount')
            this.$set(this, 'purchaseList', list)
          })
        } else {
          await this.hmpay({
            orderIds: ids.join(','),
            type: 'notPay'
          })
          this.$store.dispatch('user/getCartGoodCount')
          this.getList()
        }

        return
      }
      const recordArr = this.isOkList
      for (let i = 0; i < recordArr.length; i++) {
        const v = recordArr[i]
        await updateWarehouseStatus({
          orderId: v.id,
          currentSaleStatus: v.saleStatus
        })
      }
      this.getList()
    },
    async settlePurchase() {
      const target = this.purchaseList.find((item) => item.checked)
      const { code } = await settleCart({ orderId: target ? target.id : '' })
      if (code === 200) {
        this.getList()
      }
    },
    async addShelves(type) {
      let target
      if (type === 'add') {
        target = this.purchaseList.find((item) => item.checked)
      }
      const res = await checkAddReq({ orderId: target ? target.id : '' })
      const { map } = res
      if (map && map.data) {
        const timeNow = new Date().getTime()
        const mapData = map.data
        const shelveEndDateTime = mapData.shelveEndDateTime
        const shelveStartDateTime = mapData.shelveStartDateTime
        this.timeFlag =
          timeNow <= shelveEndDateTime && timeNow >= shelveStartDateTime
      }
      if (type === 'add') {
        this.getList()
      }
    },
    // get list
    async getList() {
      getCartList().then((res) => {
        const { data } = res.map
        // this.list = data;
        this.$set(this, 'list', data)
        console.log('data:', data)
        this.isSkeletonShow = false
      })
      getPurchaseProductList().then((res) => {
        // const { map: { records }} = res
        const list = res.map.list
        const purchaseList = list.reduce((result, item) => {
          item.goodsPrice = item.goodsPrice * item.goodsCount
          if (item.orderPayNoUrl === undefined) {
            item.orderPayNoUrl = null
          }
          result.push(item)
          return result
        }, [])
        this.$set(this,'purchaseList',purchaseList)
      })
    },
    async getPurchaseProductDataList() {
      const { map } = await getPurchaseProductList()
      const { records } = map
      this.purchaseList = records.reduce((result, item) => {
        item.goodsPrice = item.goodsPrice * item.goodsCount
        // debugger
        result.push(item)
        return result
      }, [])
      this.purchaseList = this.purchaseList.filter(
        (item) => item.saleStatus !== 2
      )
    },
    // single select
    handleItemSelect(playload, type, index, checked) {
      console.log(playload, type, index, checked)
      if (!type) {
        const { val, idx } = playload
        const arr = this.list.filter((item) => {
          return item.id === idx
        })
        const index = this.list.findIndex((item) => {
          return item.id === idx
        })
        const data = { id: idx, checked: val }
        updateCart(data)
          .then((res) => {
            const newval = arr[0]
            newval.checked = val
            this.$set(this.list, index, newval)
          })
          .catch((e) => { })
      } else {
        this.purchaseList.map((item) => {
          item.index = ''
          // item.checked = false;
        })
        this.purchaseList[index].index = index
        this.purchaseList[index].checked = !checked
        this.$set(this.purchaseList, index, this.purchaseList[index])
      }
    },
    // all select
    handleAllSelect(value) {
      console.log(value)
      this.list
        .filter((item) => {
          return item.maxNum >= item.number
        })
        .map((item) => {
          const data = { id: item.id, checked: value }
          updateCart(data)
            .then((res) => { })
            .catch((e) => { })
          item.checked = value
          return item
        })
      this.list.forEach((item, i) => {
        this.$set(this.list, i, item)
      })
    },
    // item delete
    handleDelete(idx) {
      this.$toast.loading({
        message: '加载中...',
        overlay: true,
        duration: 0,
        forbidClick: true
      })
      console.log('idx==', idx)
      deleteCart(idx)
        .then((res) => {
          this.$toast.clear()
          this.$toast.success('删除成功')
          const index = this.list.findIndex((item) => item.id === idx)

          this.list.splice(index, 1)
          this.list.forEach((item, i) => {
            this.$set(this.list, i, item)
          })
          // sessionStorage.setItem('refresh',true)
          this.$store.dispatch('user/getCartGoodCount')
          // sessionStorage.setItem('isCartRefresh', true)
          console.log(this.list)
        })
        .catch((e) => {
          console.log(e)
        })
    },
    // 是否可删除
    async canIDelete() {
      const res = await canIDel()
      console
      return res.map.isOpen == 1 ? false : true
    },
    async handleDeletePurchase(idx) {
      const flag = await this.canIDelete()
      if (!flag) {
        return this.$toast.fail('已完成调单，无法删除订单')
      }
      this.$toast.loading({
        message: '加载中...',
        overlay: true,
        duration: 0,
        forbidClick: true
      })
      console.log('idx==', idx)
      let data = 0
      this.purchaseList.forEach((item, index) => {
        if (item.id === idx) {
          data = this.purchaseList[index]
        }
      })
      console.log('idx==', data)
      const res = await deletePurchaseCart(data)
      console.log(res)
      if (res.code === 200) {
        // debugger
        this.$toast.clear()
        this.$toast.success('删除成功')
        const index = this.purchaseList.findIndex((item) => item.id === idx)
        // this.$emit('getCartGoodsCount')
        // sessionStorage.setItem('refresh',true)
        this.$store.dispatch('user/getCartGoodCount')

        this.purchaseList.splice(index, 1)
        this.purchaseList.forEach((item, i) => {
          this.$set(this.purchaseList, i, item)
        })
        console.log(this.purchaseList)
      }
    },
    async changeNum(id, num) {
      let newval
      this.list.forEach((item) => {
        if (item.id === id) {
          item.number = num
          newval = item
        }
      })
      const index = this.list.findIndex((item) => {
        return item.id === id
      })
      // vue动态更新list集合

      this.$set(this.list, index, newval)
      await this.getList()
    },
    async hmpay(data) {
      const res = await orderProcurementHmpay(data)
      console.log(res)
      this.$store.dispatch('user/getCartGoodCount')
      if (data.type) {
        return this.$router.push('/user/order/warehouseList/1?type=1')
      } else {
        const datas = res.map.result
        this.payUrl = datas
        // location.assign(this.payUrl);
        window.open(datas, '_self');
        // this.$router.push('/transfer?src=' + data)
        console.log(datas)
        
        // this.$router.push('/transfer?src=' + data)
        // const newWindow = window.open('', '_self');
        // window.open(this.payUrl,'_self')

        // 写入数据到新窗口
        // newWindow.document.write(datas);

        // 如果需要执行数据中的JavaScript代码，可以使用eval()
        // newWindow.document.close(); // 关闭文档，确保所有资源都加载完毕
        // newWindow.eval(newWindow.document.getElementsByTagName('script')[0].innerText);
        // location.href = data
        // window.location.href = datas

        // this.$router.push('/transfer?src=' + datas)
        // window.open(datas, '_self')
        this.isPay = false
      }

      // this.$router.replace({
      //   name: 'PayStatus',
      //   params: {
      //     orderType: 'procurement',
      //     status: 'pending',
      //     orderNo: recordId
      //   }
      // })
      // this.purchaseList.map(async(item) => {
      //   await updateWarehouseStatus({
      //     orderId: item.id,
      //     payPicUrl: this.urls,
      //     currentSaleStatus: 3
      //   })
      // })

      // .catch(async() => {
      //   const recordArr = this.isOkList
      //   for (let i = 0; i < recordArr.length; i++) {
      //     const v = recordArr[i]
      //     await updateWarehouseStatus({
      //       orderId: v.id,
      //       payPicUrl: this.urls,
      //       currentSaleStatus: 1
      //     })
      //   }
      //   this.$router.replace({
      //     name: 'PayStatus',
      //     params: {
      //       status: 'failed'
      //     }
      //   })
      //   this.$dialog.alert({ message: '支付失败' })
      // })
    }
  }
}
</script>

<style scoped lang="scss">
.product-title {
  color: #333;
  font: bolder;
  font-size: 22px;
  margin: 18px 0 0 18px;
}

.product-header {
  display: flex;
  align-items: center;
}
</style>_res_e_res_e_res_err_$event
